<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		errorModal,
		ignoreHtml,
		getUrl,
		confirmModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		changeConfigAttr,
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	import moment from '@/static/js/moment.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				projectDataShowIdCacheKey: 'hr-train-trainsign-projectdatashowid-cache',
				signMainUserIdCacheKey: 'hr-train-trainsign-signmainuserid-cache',
				signStartDateInit: '',
				signEndDateInit: '',
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		methods:{
			startDateChange(data){
				let _that = this
				let start = data+':00'
				let startstr = new Date(start).getTime()
				let end = _that.$refs.autoform.formdata.endDate ? _that.$refs.autoform.formdata.endDate+':00':''
				let endstr = new Date(end).getTime()
				let cmin = (endstr-startstr) / 1000 / 60
				_that.$refs.autoform.formdata.dataTimeNum = cmin
			},
			endDateChange(data){
				let _that = this
				let start = _that.$refs.autoform.formdata.startDate ? _that.$refs.autoform.formdata.startDate+':00':''
				let startstr = new Date(start).getTime()
				let end = data+':00'
				let endstr = new Date(end).getTime()
				let cmin = (endstr-startstr) / 1000 / 60
				_that.$refs.autoform.formdata.dataTimeNum = cmin
			},
			clearProjectDataShow(){
				this.$refs.autoform.clear("title1","projectDataShowId")
				this.$refs.autoform.clear("title1","teacherId")
				this.$refs.autoform.clear("title1","placeId")
				this.$refs.autoform.clear("title1","startDate")
				this.$refs.autoform.clear("title1","endDate")
				this.$refs.autoform.clear("title1","dataTimeNum")
				this.$refs.autoform.clear("title1","projectTypeId")
				this.$refs.autoform.clear("title1","projectId")
				this.$refs.autoform.clear("title1","projectName")
				this.$refs.autoform.clear("title1","trainTypeId")
				this.$refs.autoform.clear("title1","partakeUserNum")
				this.$refs.autoform.clear("title1","projectScoreNum")
				this.$refs.autoform.clear("title2","content")
				this.$refs.autoform.clear("title3","trainObj")
				this.$refs.autoform.clear("title4","relevantAbilityIdStr")
				this.$refs.autoform.clear("title4","relevantAbilityNameStr")

				let dataList = []
				this.subEditorObj["title5"].workList = dataList
				this.$refs.autoform.$set(this.$refs.autoform.formdata,"dataUserStr",JSON.stringify(dataList))
				this.$set(this.formdata,'dataUserStr',JSON.stringify(dataList))
				
				this.$refs.autoform.formdata.signStartDate = ''
				this.$refs.autoform.formdata.signEndDate = ''
			},
			getSignTime(num, time){
				let _that = this
				let timeCode = ''
				if(num == 1){
					timeCode = 'DD033002'
				}
				if(num == 2){
					timeCode = 'DD033003'
				}
				_that.om.request('/dataDict/getIntByCode', {
					code: timeCode
				}).then(res => {
					if(res.succeed == true){
						let d = res.value;
						let starttime = new Date(time).getTime();
						let qtime = d * 60 * 1000;
						let rtime = '';
						if(num == 1){
							rtime = starttime - qtime;
							_that.$refs.autoform.formdata.signStartDate = _that.moment(rtime).format("YYYY-MM-DD HH:mm");
						}
						if(num == 2){
							rtime = starttime + qtime;
							_that.$refs.autoform.formdata.signEndDate = _that.moment(rtime).format("YYYY-MM-DD HH:mm");
						}
					}else{
						_that.om.toast(res.msg);
					}
				})
				return 
			},
			initLoad(options){
				let _that = this
				let fileId = options.fileId
				let ajaxArr = [
					urlUtil.zposUrl(options.code)
				]
				if(fileId){
					ajaxArr.push({
						url:"trainSign/getValue",
						param:{
							fileId:fileId
						}
					})
				}
				formModelLoad(ajaxArr,function(res,mainData){
					changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posname'), mainData);
					_that.$nextTick(function(){
						// _that.$refs.autoform.initZposId()
						if(res[0].length == 1){
						 	_that.$refs.autoform.initSelectIndex('topinfo', 'zposId')
						 	_that.$set(_that.formdata, 'zposId', res[0].id)
						 	_that.$set(_that.formdata, 'zposName', res[0].posname)
						}
					})
					
					changeEditor("title1","projectDataShowId",{
						link:"../../public/pageSearch/pageSearch",
						"linkParam": {
							other:JSON.stringify({
								oldValue: ""
							}),
							namefield:'joinDataContent',
							searchfield:"q",
							initload:true,
							url:'trainNoticeShow/findUnSignPager',
							cachename:_that.projectDataShowIdCacheKey,
							placeholder:"请输入培训课节"
						}
					},null,mainData)
					changeEditor('title1',"signMainUserId","isSearchUser",true,mainData)
					changeEditor('title1',"signMainUserId",{
						link:'../../public/searchUser/searchUser',
						"linkParam":{
							cachename: _that.signMainUserIdCacheKey,
							isSingle:true
						}
					},null,mainData),
					changeEditor("title5", "dataUserStr", {
						titleTemplate: "  <%= userName %>",
						subtitle1Template: "<%= postName %>",
						subtitle2Template: "<%= '签到时间：'+ (signDate ? signDate : '') %>"
					}, null, mainData)
					
					_that.subEditorObj["title5"].showAdd = false
					_that.subEditorObj["title5"].showDel = false
					
					if(fileId) {
						let fileIdArr = getFormFields(mainData)
						fileIdArr.push("id")
						for(let index in res[1].value){
							if(fileIdArr.includes(index)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[1].value[index])
								_that.$set(_that.formdata,index,res[1].value[index])
							}
						}
						_that.signStartDateInit = _that.$refs.autoform.formdata.signStartDate
						_that.signEndDateInit =  _that.$refs.autoform.formdata.signEndDate
						let dataList = _that._.cloneDeep(res[1].value.dataUserList)
						_that.subEditorObj["title5"].workList = dataList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataUserStr",JSON.stringify(dataList))
						_that.$set(_that.formdata,'dataUserStr',JSON.stringify(dataList))
						delete res[1].value.dataUserList
						_that.$nextTick(function(){
							_that.$refs.autoform.changeEditor("topinfo","zposId","type","labelbox")
							_that.$refs.autoform.changeEditor("title1","projectDataShowId","type","labelbox")
						})
					}
				},options)
			},
			formSubmit() {
				let _that = this;
				if(_that.edit){
					if((_that.signStartDateInit != _that.$refs.autoform.formdata.signStartDate) || (_that.signEndDateInit != _that.$refs.autoform.formdata.signEndDate)){
						uni.showModal({
							title: '',
							content: '签到开始时间、签到结束时间，保存后都将清空签到信息记录，是否继续保存？',
							showCancel: true,
							success(res){
								if(res.confirm){
									_that.om.formSave('/trainSign/doUpdate',_that.formdata,_that)
								}
							}
						})
					}else{
						_that.om.formSave('/trainSign/doUpdate',_that.formdata,_that)
					}
				}else{
					_that.om.request(
						"posBusiAuth/verifyOne",
						{
							busCode:_that.busCode,
							isNew:false
						}
					).then(res=>{
						if(res.succeed){
							_that.om.formSave('/trainSign/doAdd',_that.formdata,_that)
						}else{
							_that.om.toast(res.msg)
						}
					})
					
				}
			}
		},
		onLoad(options) {
			let _that = this
			_that.initLoad(options)
		},
		onShow() {
			let _that = this
			for (var fieldId in _that.subEditorObj) {
				let editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						if(res.data.length>0){
							for(let i=0; i<res.data.length; i++){
								res.data[i].shouldPartakeFlag = res.data[i].shouldPartakeFlag == '√' ? true : ''
								res.data[i].leaveFlag = res.data[i].leaveFlag == '√' ? true : ''
								res.data[i].truancyFlag = res.data[i].truancyFlag == '√' ? true : ''
								res.data[i].lateFlag = res.data[i].lateFlag == '√' ? true : ''
							}
						}
						editor.workList = res.data;
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			if(_that.$refs.autoform){
				uni.getStorage({
					key: _that.projectDataShowIdCacheKey,
					success: function(res) {
						if(res.data){
							let d = res.data
							var formdata  = _that.$refs.autoform.formdata
							formdata.projectDataShowId = d.id
							formdata.projectDataShowName = d.joinDataContent
							formdata.teacherId = d.teacherId
							formdata.teacherName = d.teacherName
							formdata.placeId = d.placeId
							formdata.placeName = d.placeName
							formdata.startDate = d.startDate
							formdata.endDate = d.endDate
							formdata.dataTimeNum = d.dataTimeNum
							_that.getSignTime(1, d.startDate)
							_that.getSignTime(2, d.startDate)
							
							_that.om.request('/trainSign/getDataBySubDataId', {
								trainNoticeDataShowId: d.id
							}).then(res => {
								if(res.succeed == true){
									let sd = res.value
									formdata.projectTypeId = sd.projectTypeId
									formdata.projectTypeName = sd.projectTypeName
									formdata.projectId = sd.projectId
									formdata.projectName = sd.projectName
									formdata.trainTypeId = sd.trainTypeId
									formdata.trainTypeName = sd.trainTypeName
									formdata.partakeUserNum = sd.partakeUserNum
									formdata.projectScoreNum = sd.projectScoreNum
									formdata.content = sd.content
									formdata.trainObj = sd.trainObj
									formdata.relevantAbilityIdStr = sd.relevantAbilityIdStr
									formdata.relevantAbilityNameStr = sd.relevantAbilityNameStr

									let dataList = _that._.cloneDeep(sd.dataUserList)
									_that.subEditorObj["title5"].workList = dataList
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataUserStr",JSON.stringify(dataList))
									_that.$set(_that.formdata,'dataUserStr',JSON.stringify(dataList))
									_that.subEditorObj["title5"].showAdd = false
									_that.subEditorObj["title5"].showDel = false
									delete sd.dataUserList
								}else{
									_that.om.toast(res.msg);
								}
							})
							uni.removeStorage({
								key: _that.projectDataShowIdCacheKey
							});
						}
					}
				});
				uni.getStorage({
					key: _that.signMainUserIdCacheKey,
					success: function(res) {
						if(res.data){
							let d = res.data[0]
							var formdata  = _that.$refs.autoform.formdata
							formdata.signMainUserId = d.id
							formdata.signMainUserName = d.username
							uni.removeStorage({
								key: _that.signMainUserIdCacheKey
							});
						}
					},
				});
			}
		}
	}
</script>                                                                                                                                                                                                                                                                                                                
